<template>
  <div>
    <article class="innerPage bookList">
      <!-- <header class="breadcrumb">
        <x-breadcrumb
          :path="$route.path"
          :title="$route.meta.breadcrumb"
          :startIndex="$route.meta.startIndex"
        >
        </x-breadcrumb>
      </header> -->
      <div class="section-title">{{ title }}通知</div>
      <section style="padding-top: 20px">
        <div class="from_post">
          <el-form label-width="120px" :model="rowData" :rules="rules" ref="ruleForm">
            <el-form-item label="是否批量推送" prop="node">
              <el-radio-group v-model="rowData.node" @change="showNode">
                <el-radio :label="1">批量推送</el-radio>
                <el-radio :label="2">微信限制</el-radio>
                <el-radio :label="3">读者证号限制</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择微信：" v-if="rowData.node == 2" class="is-required">
              <el-input class="input_num3" v-model="appointUser" placeholder="请输入用户微信昵称"></el-input>
              <el-button class="zhi-btn" @click="remoteMethod()">确定</el-button>
              <p style="color: red">请输入用户微信昵称进行搜索，可多次选择</p>
            </el-form-item>
            <el-form-item label="已选微信：" v-if="appoint_userArr.length !== 0">
              <div class="tabContent-box">
                <div class="content-boxUser" v-for="(item, index) in appoint_userArr" :key="index">
                  <div class="img-text">
                    <div class="content-img">
                      <a target="_blank" :href="item.head_img">
                        <img :src="item.head_img" alt="" class="img-a" />
                      </a>
                    </div>
                    <div class="content-text">
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="微信昵称" placement="top">
                          <span>{{ item.nickname }}</span>
                        </el-tooltip>
                      </p>
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="读者证号" placement="top">
                          <span>{{ item.account }}</span>
                        </el-tooltip>
                      </p>
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="读者证姓名" placement="top">
                          <span>{{ item.username }}</span>
                        </el-tooltip>
                      </p>
                    </div>
                  </div>
                  <p class="del-p" @click="deleteBtn(index)">删除</p>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="选择读者：" v-if="rowData.node == 3" class="is-required">
              <el-input class="input_num3" v-model="readerUser" placeholder="请输入读者证号"></el-input>
              <el-button class="zhi-btn" @click="readerMethod()">确定</el-button>
              <p style="color: red">请输入读者证号进行搜索，可多次选择</p>
            </el-form-item>
            <el-form-item label="已选读者：" v-if="reader_userArr.length !== 0">
              <div class="tabContent-box">
                <div class="content-boxUser" v-for="(item, index) in reader_userArr" :key="index">
                  <div class="img-text">
                    <div class="content-img">
                      <a target="_blank" :href="item.head_img">
                        <img :src="item.head_img" alt="" class="img-a" />
                      </a>
                    </div>
                    <div class="content-text">
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="微信昵称" placement="top">
                          <span>{{ item.nickname }}</span>
                        </el-tooltip>
                      </p>
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="读者证号" placement="top">
                          <span>{{ item.account }}</span>
                        </el-tooltip>
                      </p>
                      <p class="text-p2">
                        <el-tooltip class="item" effect="dark" content="读者证姓名" placement="top">
                          <span>{{ item.username }}</span>
                        </el-tooltip>
                      </p>
                    </div>
                  </div>
                  <p class="del-p" @click="readerdeteBtn(index)">删除</p>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input v-model="rowData.content" placeholder="请输入内容" type="textarea" :rows="3" maxlength="100" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="服务类型" prop="type_name">
              <el-input v-model="rowData.type_name" placeholder="请输入服务类型" type="textarea" :rows="2" maxlength="50" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="时间" class="is-required">
              <div class="tiem_class">
                <el-form-item prop="start_time">
                  <el-date-picker type="date" placeholder="开始时间" v-model="rowData.start_time" style="width: 195px" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <div class="tiem_class_line">～</div>
                <el-form-item>
                  <el-date-picker type="date" placeholder="结束时间" v-model="rowData.end_time" style="width: 195px" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <!--  -->
              </div>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="rowData.remark" placeholder="请输入备注" type="textarea" :rows="4" maxlength="150" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="链接">
              <el-input v-model="rowData.link" placeholder="请输入链接" type="textarea" :rows="4" maxlength="120" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="是否立即发送" prop="is_send" v-if="title == '添加'">
              <el-radio-group v-model="rowData.is_send">
                <el-radio :label="1">立即发送</el-radio>
                <el-radio :label="2">后续发送</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item>
              <div style="padding: 10px 0 20px 0" class="btn_el">
                <el-button @click="submitForm('ruleForm')" class="btn_establish">
                  确认
                </el-button>
                <el-button class="btn_cancel" @click="can">取消</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </section>
    </article>
    <!-- 用户列表弹框 -->
    <specifyUserPup ref="isSpecify" @userAdd="userAdd" />
  </div>
</template>

<script>
import specifyUserPup from './specifyUserPup.vue'
export default {
  components: { specifyUserPup },
  data() {
    return {
      title: '',
      rules: {
        node: [
          { required: true, message: '请选择是否批量推送', trigger: 'change' }
        ],
        start_time: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        type_name: [
          { required: true, message: '请输入服务类型', trigger: 'blur' }
        ],
        is_send: [
          { required: true, message: '请选是否立即发送', trigger: 'blur' }
        ]
      },
      rowData: {
        node: 1,
        content: '',
        type_name: '',
        start_time: '',
        end_time: '',
        account_id: '',
        remark: '',
        link: '',
        wechat_id: '',
        is_send: 1
      },
      editId: '',
      appointUser: '',
      duration: '1s',
      readerUser: '',
      appoint_userArr: [],
      reader_userArr: []
    }
  },
  mounted() { },
  activated() {
    if (this.$route.query?.action != "refresh" || this.$isFirstInPage.get()) {
      this.resetData()
      if (this.$route.query.id) {
        this.editId = this.$route.query.id
        this.getDetail()
        this.title = '修改'
      } else {
        this.editId = ''
        this.title = '添加'
      }
    }

    this.setPageTabs()
  },
  methods: {
    resetData() {
      this.rowData = {
        node: 1,
        content: '',
        type_name: '',
        start_time: '',
        end_time: '',
        account_id: '',
        remark: '',
        link: '',
        wechat_id: '',
        is_send: 1
      }
      this.readerUser = ''
      this.reader_userArr = []
      this.appointUser = ''
      this.appoint_userArr = []
    },
    // 详情
    async getDetail() {
      try {
        let res = await this.request({
          url: '/admin/serviceNotice/detail',
          method: 'get',
          loading: true,
          data: {
            id: this.editId
          }
        })
        if (res) {
          this.rowData = {
            node: res.content.node,
            content: res.content.content,
            type_name: res.content.type_name,
            start_time: res.content.start_time,
            end_time: res.content.end_time || '',
            account_id: res.content.account_id,
            remark: res.content.remark,
            link: res.content.link,
            is_send: res.content.is_send
          }
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    //返回列表
    can() {
      this.$router.push({
        path: '/SystemSettings/serviceReminder'
      })
    },
    //表单提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.rowData.node == 1) {
            //批量推送
            this.rowData.account_id = ''
            this.rowData.wechat_id = ''
          } else if (this.rowData.node == 2) {
            //微信限制
            this.rowData.account_id = ''
            if (this.appoint_userArr.length == 0) {
              this.$message.warning('请选择用户微信')
            } else {
              let wechatArr = []
              this.appoint_userArr.forEach(item => {
                wechatArr.push(item.wechat_id)
              })
              this.rowData.wechat_id = wechatArr.join(',')
            }
          } else if (this.rowData.node == 3) {
            //读者证号限制
            this.rowData.wechat_id = ''
            if (this.reader_userArr.length == 0) {
              this.$message.warning('请选择读者证')
            } else {
              let accountArr = []
              this.reader_userArr.forEach(item => {
                accountArr.push(item.account_id)
              })
              this.rowData.account_id = accountArr.join(',')
            }
          }
          this.postList()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async postList() {
      let urls = ''
      if (this.title == '修改') {
        urls = '/admin/serviceNotice/change'
        this.rowData.id = this.editId
      } else {
        urls = '/admin/serviceNotice/add'
      }
      try {
        let res = await this.request({
          url: urls,
          method: 'post',
          loading: true,
          data: {
            ...this.rowData
          }
        })
        if (res) {
          this.$message.success(res.msg)
          setTimeout(() => {
            this.$router.push({
              path: '/SystemSettings/serviceReminder'
            })
          }, 1000)
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    // 微信
    remoteMethod() {
      if (this.appointUser) {
        this.getPicture()
      } else {
        this.$message.warning('请输入用户微信昵称搜索')
      }
    },
    // 获取指定微信用户列表
    async getPicture() {
      try {
        let res = await this.request({
          url: '/admin/userInfo/list',
          method: 'get',
          loading: true,
          data: {
            page: 1,
            limit: 9999,
            keywords: this.appointUser,
            keywords_type: 5
          }
        })
        if (res) {
          this.$refs.isSpecify.showModal({
            pictureArr: res.content.data,
            appoint_userArr: this.appoint_userArr
          })
        }
      } catch (err) {
        let error = err.message.split('/')
        this.$message.error(error[1])
      }
    },
    // 删除选择微信用户
    deleteBtn(index) {
      this.appoint_userArr.splice(index, 1)
    },
    // 读者证
    readerMethod() {
      if (this.readerUser) {
        this.getReader()
      } else {
        this.$message.warning('请输入用户微信昵称搜索')
      }
    },
    // 获取指定读者证列表
    async getReader() {
      try {
        let res = await this.request({
          url: '/admin/userInfo/list',
          method: 'get',
          loading: true,
          data: {
            page: 1,
            limit: 9999,
            keywords: this.readerUser,
            keywords_type: 1
          }
        })
        if (res) {
          this.$refs.isSpecify.showModal({
            pictureArr: res.content.data,
            appoint_userArr: this.appoint_userArr
          })
        }
      } catch (err) {
        let error = err.message.split('/')
        this.$message.error(error[1])
      }
    },
    // 用户选择返回
    userAdd(val) {
      if (this.rowData.node == 2) {
        // 微信
        if (val.length > 0) {
          val.map(item => {
            this.appoint_userArr.push(item)
          })
        }
        // 过滤重复数据
        for (let i = 0; i < this.appoint_userArr.length; i++) {
          for (let j = i + 1; j < this.appoint_userArr.length; j++) {
            if (
              this.appoint_userArr[i].id == this.appoint_userArr[j].id ||
              this.appoint_userArr[i].user_id == this.appoint_userArr[j].id
            ) {
              this.appoint_userArr.splice(j, 1)
              j--
            }
          }
        }
      } else if (this.rowData.node == 3) {
        // 读者
        if (val.length > 0) {
          val.map(item => {
            this.reader_userArr.push(item)
          })
        }
        // 过滤重复数据
        for (let i = 0; i < this.reader_userArr.length; i++) {
          for (let j = i + 1; j < this.reader_userArr.length; j++) {
            if (
              this.reader_userArr[i].id == this.reader_userArr[j].id ||
              this.reader_userArr[i].user_id == this.reader_userArr[j].id
            ) {
              this.reader_userArr.splice(j, 1)
              j--
            }
          }
        }
      }
    },
    // 删除选择读者用户
    readerdeteBtn(index) {
      this.reader_userArr.splice(index, 1)
    },
    showNode(val) {
      if (val == 1) {
        this.appoint_userArr = []
        this.reader_userArr = []
      } else if (val == 2) {
        this.readerUser = ''
        this.reader_userArr = []
      } else if (val == 3) {
        this.appointUser = ''
        this.appoint_userArr = []
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
